﻿ /***********************************************************************
  * Author：rjdong@wind.com.cn  
  * CreateDate：2012/12/18 11:25:49
  * Function：
  * *********************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

using Wind.Utils;

namespace Wind.Cloud.Tools
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// id计数器
        /// </summary>
        public static int nBase = 0;

        int listN = 0;
        /// <summary>
        /// 指标Function Dict
        /// </summary>
        public Dictionary<int, FunctionBaseInfo> BaseInfoDict = new Dictionary<int, FunctionBaseInfo>();
        public Dictionary<int, FunctionBaseInfo> BaseInfoDictReady = new Dictionary<int, FunctionBaseInfo>();

        /// <summary>
        /// 指标自动完成DataTable
        /// </summary>
        DataTable dtBaseInfo = new DataTable();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string fileName = Application.StartupPath + "\\Cloud Function.txt";
            init(fileName);
            for (var i = 0; i < BaseInfoDict.Count; i++)
            {
                this.list_Auto.Items.Add(BaseInfoDict[i].Id + " " + BaseInfoDict[i].Name + " " + BaseInfoDict[i].NameCN);
            }
        }


        /// <summary>
        /// import function txt file
        /// </summary>
        /// <param name="fileName"></param>
        private void LoadFunctionToDB(string fileName)
        {
            try
            {
                if (File.Exists(fileName))
                {
                    string functionStr = string.Empty;
                    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        string str = string.Empty;
                        using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                        {
                            int i = 0;
                            //while ((str = sr.ReadLine()) != null)
                            while (sr.Peek() >= 0)
                            {
                                i++;
                                str = sr.ReadLine();
                                insertDB(str);
                            }
                            sr.Close();
                            int n = i+1;
                        }
                        fs.Close();
                    }                   
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write("Wind.Cloud.Tools.LoadFunctionToDB() error", ex);
            }
        }

        private void insertDB(string funStr)
        {
            if (!string.IsNullOrEmpty(funStr))
            {
                FunctionBaseInfo baseInfo = new FunctionBaseInfo();

                //(流动负债差额(合计平衡项目))function name=s_stm07_bs_91 windCode=[value] rptDate=[value] rptType=[value]
                string[] flags1 = { "=" };
                string[] flags2 = { " " };

                string[] tags = funStr.Split(flags1, StringSplitOptions.RemoveEmptyEntries);
                if (tags.Length > 0)
                {
                    int n = funStr.ToLower().IndexOf("function");
                    baseInfo.Id = nBase++;
                    //中文名称，去掉括号
                    //baseInfo.NameCN = funStr.Substring(1, n - 2);
                    baseInfo.NameCN = funStr.Substring(0, n);
                    //baseInfo.NamePY = Wind.Utils.PinYinHelper.GetPinYin(baseInfo.NameCN);
                    
                    string[] ss = tags[1].Split(flags2, StringSplitOptions.RemoveEmptyEntries);
                    baseInfo.Name = ss[0];
                    baseInfo.FunctionStr = funStr;
                    BaseInfoDict.Add(baseInfo.Id, baseInfo);
                    /*
                    for (int i = 2; i < tags.Length; i++)
                    {
                        metaInfo.Id = nMeta++;
                        metaInfo.BaseId = baseInfo.Id;
                        ss = tags[i].Split(flags2, StringSplitOptions.RemoveEmptyEntries);
                        metaInfo.Name = ss[0];

                        MetaInfoList.Add(metaInfo);
                    }
                     */
                }
                this.richTextBox1.AppendText(funStr + "\r\n");
            }
        }

        private void Btn_CloudImport_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                init(this.openFileDialog1.FileName);
            }
        }

      
        private void txt_FunctionName_KeyUp(object sender, KeyEventArgs e)
        {
            string key = this.txt_FunctionName.Text;
            //this.Text = key;
            if (dtBaseInfo.Rows.Count == 0) return;

            DataRow[] drs1 = dtBaseInfo.Select("Name like '" + key + "*'");
            DataRow[] drs2 = dtBaseInfo.Select("NameCN like '" + key + "*'");
            DataRow[] drs3 = dtBaseInfo.Select("NamePY like '" + key + "*'");
            
            AutoCompleteStringCollection autoCol = new AutoCompleteStringCollection();
            if (drs1.Length > 0)
            {
                this.list_Auto.Items.Clear();
           
                for (var i = 0; i < drs1.Length; i++)
                {
                    this.list_Auto.Items.Add(drs1[i]["Display"]);
                    autoCol.Add(drs1[i]["Display"].ToString());               
                }
            }
            else if (drs2.Length > 0)
            {
                this.list_Auto.Items.Clear();
           
                for (var i = 0; i < drs2.Length; i++)
                {
                    this.list_Auto.Items.Add(drs2[i]["Display"]);
                    autoCol.Add(drs2[i]["Display"].ToString());
                }
            }
            else if (drs3.Length > 0)
            {
                this.list_Auto.Items.Clear();
           
                for (var i = 0; i < drs3.Length; i++)
                {
                    this.list_Auto.Items.Add(drs3[i]["Display"]);
                    autoCol.Add(drs3[i]["Display"].ToString());
                }
            }
            //this.list_FunctionNameList.SelectedIndex = 0;

            this.txt_FunctionName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            this.txt_FunctionName.AutoCompleteSource = AutoCompleteSource.CustomSource;
            this.txt_FunctionName.AutoCompleteCustomSource = autoCol;

            if (e.KeyCode == Keys.Enter)
            {
                this.list_Auto.Focus();
                if (this.list_Auto.SelectedItem != null)
                    this.txt_FunctionName.Text = this.list_Auto.SelectedItem.ToString();
            }
            if (e.KeyCode == Keys.Up)
            {
                listN--;
                if (listN <= 0) listN = this.list_Auto.Items.Count - 1;
                this.list_Auto.SelectedIndex = listN;
            }
            if (e.KeyCode == Keys.Down)
            {
                listN++;
                if (listN >= this.list_Auto.Items.Count)
                    listN = 0;
                this.list_Auto.SelectedIndex = listN;
            }
            if (e.KeyCode == Keys.PageUp)
            {
                this.list_Auto.SelectedIndex = 0;
            }
            if (e.KeyCode == Keys.PageDown)
            {
                this.list_Auto.SelectedIndex = this.list_Auto.Items.Count - 1;
            }
        }

       
        private void init(string fileName)
        {
            nBase = 0;
            //nMeta = 0;
            BaseInfoDict.Clear();
            BaseInfoDictReady.Clear();
            //MetaInfoList.Clear();
            this.richTextBox1.Clear();

            LoadFunctionToDB(fileName);


            /*
            AutoCompleteStringCollection autoCol=new AutoCompleteStringCollection();
            foreach (KeyValuePair<string, FunctionBaseInfo> kv in BaseInfoDict)
            {
                autoCol.Add(kv.Value.Name);
                autoCol.Add(kv.Value.NameCN);
                autoCol.Add(kv.Value.NamePY);
            }
            this.cbbFunctionName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            this.cbbFunctionName.AutoCompleteSource = AutoCompleteSource.CustomSource;
            this.cbbFunctionName.AutoCompleteCustomSource = autoCol;
             */



            dtBaseInfo = new DataTable();
            dtBaseInfo.Columns.Add("Display");
            dtBaseInfo.Columns.Add("Name");
            dtBaseInfo.Columns.Add("NameCN");
            dtBaseInfo.Columns.Add("NamePY");
            foreach (KeyValuePair<int, FunctionBaseInfo> kv in BaseInfoDict)
            {
                dtBaseInfo.Rows.Add(new string[] { kv.Value.Id + " " + kv.Value.Name + " " + kv.Value.NameCN, kv.Value.Name, kv.Value.NameCN, kv.Value.NamePY });
            }
            //DisplayMember 与ValueMember 属性的区别： 
            //DisplayMember绑定的是需显示的字段 
            //ValueMember绑定的是对应的值 
        }

        private void list_FunctionNameList_DoubleClick(object sender, EventArgs e)
        {
            if (this.list_Auto.SelectedIndex != -1)
                this.txt_FunctionName.Text = this.list_Auto.SelectedItem.ToString();     
        }

        private void btn_Matrix_Click(object sender, EventArgs e)
        {         
            if (this.list_Ready.Items.Count == 0)
                return;
           
            string matrixStr = "Matrix2 functions={0} windcode={1}";
            string windcode = "windcode";
            string wcode = "wcode";
            string funName = string.Empty;

            //(流动负债差额(合计平衡项目))function name=s_stm07_bs_91 windCode=[value] rptDate=[value] rptType=[value]
            string[] flags1 = { " " };
            string[] flags2 = { "=" };
            string[] tags1;
            string[] tags2;
            string[] tags3;
            string signStr = string.Empty;
            string funStr = string.Empty;
            StringBuilder sb =new StringBuilder();
          
            for (var i = 0; i < this.list_Ready.Items.Count; i++)
            {
                signStr = this.list_Ready.Items[i].ToString();
                tags1 = signStr.Split(flags1, StringSplitOptions.RemoveEmptyEntries);
                int id=Wind.Utils.ParseHelper.Parse<int>(tags1[0].Trim());
                funStr = this.BaseInfoDict[id].FunctionStr;
                
                tags2 = funStr.Split(flags1, StringSplitOptions.RemoveEmptyEntries);
                if (tags2.Length > 0)
                {
                    tags3 = tags2[1].Split(flags2, StringSplitOptions.RemoveEmptyEntries);
                    funName = tags3[1];//指标名
                    sb.Append(funName);
                    tags3 = tags2[2].Split(flags2, StringSplitOptions.RemoveEmptyEntries);
                    if (tags3[0].Trim().ToLower() == windcode)
                    {
                        sb.Append("(" + windcode);
                    }
                    if (tags2.Length > 3)
                    {
                        for (int j = 3; j < tags2.Length; j++)
                        {
                            tags3 = tags2[j].Split(flags2, StringSplitOptions.RemoveEmptyEntries);
                            if (tags2.Length - 1 == j)
                            {
                                sb.Append("," + tags3[0] + ");");
                            }
                            else
                            {
                                sb.Append("," + tags3[0]);
                            }
                        }
                    }
                    else
                    {
                        sb.Append(");");
                    }
                }
            }
            string sbStr = sb.ToString();
            if (sbStr.Length > 0)
                sbStr = sbStr.Substring(0, sbStr.Length - 1);
            string result = string.Format(matrixStr, sbStr, windcode);
            this.richTextBox2.Text = result;
            this.tabControl1.SelectedIndex = 1;
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txt_FunctionName.Text))
            {
                /*
                string[] flags1 = { " " };
                string[] metaStr = this.txt_FunctionName.Text.Split(flags1, StringSplitOptions.RemoveEmptyEntries);
             
            int id=Wind.Utils.ParseHelper.Parse<int>(metaStr[0].Trim());
            this.BaseInfoDictReady.Add(id, BaseInfoDict[id]);
                 * */

                //if (!this.list_Ready.Items.Contains(this.txt_FunctionName.Text))
                this.list_Ready.Items.Add(this.txt_FunctionName.Text);
            }
        }
        private void btn_AddAll_Click(object sender, EventArgs e)
        {
            //
            //foreach (ListBox item in this.list_Auto.SelectedItems)
            for (var i = 0; i < this.list_Auto.CheckedItems.Count; i++)
                this.list_Ready.Items.Add(this.list_Auto.CheckedItems[i].ToString());
        }
        private void btn_DeleteAll_Click(object sender, EventArgs e)
        {

        }

        private void btn_Up_Click(object sender, EventArgs e)
        {
            
        }

        private void btn_Down_Click(object sender, EventArgs e)
        {

        }

        private void 帮助LToolStripButton_Click(object sender, EventArgs e)
        {
            AboutBox about = new AboutBox();
            about.ShowDialog();
        }

        private void txt_FunctionName_TextChanged(object sender, EventArgs e)
        {

        }

       
       
    }
}
